#ifndef _SPI_H_
#define _SPI_H_

#define SPI_DDR DDRC
#define SPI_PORT PORTC
#define SPI_PIN PINC

#define MISO 1
#define MOSI 2
#define SCK 3
#define SS 4

#define spi_delay() _delay_us(10)
#define set(x) SPI_PORT |= (1<<x) 
#define reset(x) SPI_PORT &= ~(1<<x) 
#define bit(x,y) x & (1<<y)

// --------------
// ---- SPI -----
// --------------

void SPI_init()
{
	SPI_DDR |= (1<<MOSI) | (1<<SCK) | (1<<SS); //wyjscia
	SPI_DDR &= ~(1<<MISO);		//wejscia
	SPI_PORT &= ~(1<<MISO);		//wejscie plywajace
	SPI_PORT &= ~(1<<MOSI) | (1<<SCK) | (1<<SS);
}

void SPI_transmit(unsigned char rozkaz)
{
	set(SCK);
		spi_delay();
	reset(SCK);
		spi_delay();
	//1bit
	set(SCK);
	set(MOSI);
	set(SS);
		spi_delay();
	reset(SCK);
		spi_delay();
	//2bit
	set(SCK);
		spi_delay();
	reset(SCK);
		spi_delay();
	//3bit
	set(SCK);
	reset(MOSI);
		spi_delay();
	reset(SCK);
		spi_delay();
	
	unsigned char i;
	unsigned char odpowiedz;

	for (i = 7; i>=0; i--)
	{
		//4-11 bit
		set(SCK);
		if ( bit(rozkaz, i) )  //write pin
			set(MOSI);
		else 
			reset(MOSI);
		

			spi_delay();
		reset(SCK);
			spi_delay();
		
		if ( SPI_PIN & (1<<MISO) )
			odpowiedz |= (1<<i);
		else
			odpowiedz &= ~(1<<i);

	}

	//bit12
	unsigned char new_data = 0;

	set(SCK);
		spi_delay();
	reset(SCK);
		spi_delay();

	new_data = SPI_PIN & (1<<MISO);

	set(SCK);
	reset(SS);
		spi_delay();
	reset(SCK);
		spi_delay();

}

#endif
